package com.hk.context;

import com.hk.app.utils.YingmiOpenAPI;
import com.hk.commons.ConstantRoute;
import com.hk.commons.DateUtil;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.view.SysUserExcelView;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.SysUserExcelMsg;
import com.hk.service.sys.ISysUser;
import com.hk.yingmi.YingmiOpenAPIConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Evan on 2017/9/30.
 */
@Service
public class SysUserContext {
    private Logger logger = LoggerFactory.getLogger(SysUserContext.class);

    @Autowired
    private ISysUser sysUserService;

    @Autowired
    private YingmiOpenAPI openAPI;

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 把用户名下的客户都修改为无主客户
     * @param recommanCode 推荐码
     * @param actUserId 操作人ID
     * @return
     */
    public List<CheckInfo> multiUpdateRecommandCode(String recommanCode,Long actUserId){
        List<SysUser> relatedUsers = sysUserService.getUserByRecommendCode(recommanCode);
        List<CheckInfo> errResultList = relatedUsers.parallelStream()
                .map(
                        user -> sysUserService.updateRecommandCode("", user.getId(), actUserId)
                )
                .filter(checkInfo -> !checkInfo.getResult())
                .collect(Collectors.toList());
        return errResultList;
    }

    /**
     * 修改用户名下的客户状态（清空推荐码和修改为无主客户部）
     * @param user
     * @param actUserId
     * @return
     */
    public Boolean updateCustomStatus(SysUser user ,Long actUserId){
        if(user.getIsInside() !=1){
            return true;
        }

        List<CheckInfo> errorList = multiUpdateRecommandCode(user.getName(),actUserId);
        if(errorList.size()>0){
            return false;
        }

        if(!sysUserService.cleanRecommandCordByCode(user.getName(),actUserId)){
            return false;
        }
        return true;
    }

    /**
     * 获取用户在盈米的用户信息
     * @param user
     * @return
     */
    public String getYingMiAccountIf(SysUser user){
        if (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdentity())){
            return null;
        }

        Map<String, String> params = new HashMap<>();
        params.put("accountName", user.getRealName().trim());
        params.put("identityNo", user.getIdentity());
        return openAPI.sslGet_ByMap(YingmiOpenAPIConstant.ACCOUNT_GET_ACCOUNT_BY_IDENTITY, params, null);
    }

    /**
     * 封装系统用户导出excel的数据
     * @param userList
     * @return
     */
    public List<SysUserExcelMsg> getSysUserExcelMsg(List<SysUserExcelView> userList){
        List<SysUserExcelMsg> result = new ArrayList<>();

        userList.stream()
                .filter(view -> !((view.getTieCard() != null && view.getTieCard() ==1) && (view.getCardStatus() != null && view.getCardStatus() == 0) && view.getCloseAccount() == 0))
                .forEach(user -> {
                    SysUserExcelMsg msg = new SysUserExcelMsg();
                    copySysuserExcelToMsg(user,msg);
                    result.add(msg);
                });

        Collections.sort(result, Comparator.comparing(SysUserExcelMsg::getUserId));
        return result;

    }

    /**
     * 把视图的数据copy到msg
     * @param view
     * @param msg
     */
    private void copySysuserExcelToMsg(SysUserExcelView view,SysUserExcelMsg msg){
        msg.setUserId(view.getSysUserExcelViewId().getUserId());
        msg.setUserPhone(view.getUserPhone());
        msg.setUserRealName(view.getUserRealName());
        msg.setChannelName(view.getChannelName());
        msg.setUserOrgName(view.getUserOrgName());
        if(view.getRegistCts() != null){
            msg.setRegistCts(DateUtil.longToLongDate(view.getRegistCts()));
        }

        //如果不是理财师，职务清空
        if(view.getIsInside() != null && view.getIsInside() == 1){
            msg.setIsInside("是");
            msg.setUserPost(view.getUserPost());
        }else {
            msg.setIsInside("否");
        }

        if(view.getCloseAccount() != null && view.getCloseAccount() ==1){
            msg.setCloseAccount("是");
        }else {
            msg.setCloseAccount("否");
        }

        msg.setFinUserRealName(view.getFinUserRealName());
        msg.setFinPhone(view.getFinPhone());

        //离职状态
        if(view.getIsInside() != null && view.getIsInside() == 1){
            if(view.getOnType() != null && view.getOnType() ==1 ){
                msg.setOnType("离职");
            }{
                msg.setOnType("在职");
            }
        }else {
            msg.setOnType("客户");
        }

        int huaKang = supportCompanyCheck(view.getSupportCompany(),ConstantRoute.COMPANY_HUAKANG);
        if(huaKang > 0){
            msg.setBindFuYou("是");
        }else if (huaKang < 0){
            msg.setBindFuYou("否");
        }

        int yingMi = supportCompanyCheck(view.getSupportCompany(),ConstantRoute.COMPANY_YINGMI);
        if(yingMi > 0){
            msg.setBindYingMi("是");
        }else if(yingMi < 0) {
            msg.setBindYingMi("否");
        }

        int huoChai = supportCompanyCheck(view.getSupportCompany(),ConstantRoute.COMPANY_HUOCHAI);
        if(huoChai > 0){
            msg.setBindHuoCai("是");
        }else if(huoChai < 0) {
            msg.setBindHuoCai("否");
        }

        msg.setPaymentNo(view.getPaymentNo());
        msg.setBankName(view.getBankName());

        //测评情况
        String sql = "select scoreDesc, cts, kycPdfUrl from t_answer_info where userId = ? order by cts desc";
        List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql, new Object[] { view.getSysUserExcelViewId().getUserId() });
        DateTimeFormatter yearMonthDay = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (results.size() > 0) {
            Map<String, Object> result = results.get(0);

            LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli((Long)result.get("cts")), ZoneId.systemDefault());
            String timeString = localDateTime.format(yearMonthDay);
            msg.setScoreCts(timeString);

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime nextYear = localDateTime.plusYears(1L);

            if (now.compareTo(nextYear) <= 0) {
                msg.setScoreDesc(String.valueOf(result.get("scoreDesc")));
            } else {
                msg.setScoreDesc(String.valueOf(result.get("scoreDesc")) + "已过期");
            }
        } else {
            msg.setScoreDesc("未测评");
            msg.setScoreCts("");
        }
    }

    /**
     * 查看对应绑卡状态，大于0是已绑，小于0是已解绑，等于0是末绑
     * @param supportCompany
     * @type
     * @return
     */
    private int supportCompanyCheck(String supportCompany,int type){
        if(StringUtils.isBlank(supportCompany)){
            return 0;
        }

        switch (type){
            case ConstantRoute.COMPANY_HUAKANG:
                return Integer.valueOf(supportCompany.split(",")[0]);

            case ConstantRoute.COMPANY_HUOCHAI:
                return Integer.valueOf(supportCompany.split(",")[1]);

            case ConstantRoute.COMPANY_YINGMI:
                return Integer.valueOf(supportCompany.split(",")[2]);

            default:
                return 0;

        }
    }

}
